package com.ironman.original;

import cn.hutool.core.util.StrUtil;
import com.ironman.event.properties.SysTrainingProperties;
import com.ironman.original.generator.OriginalDataGenerator;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.iot.mqtt.codec.MqttQoS;
import net.dreamlu.iot.mqtt.core.client.MqttClient;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.function.Consumer;

@Slf4j
@Component
public class OriginalDataFactory {

    @Resource
    MqttClient mqttClient;

    @Resource
    SysTrainingProperties sysTrainingProperties;

    @Resource
    List<OriginalDataGenerator> originalDataGenerators;

    @PostConstruct
    public void init() {
        String topic = StrUtil.format("mobile/up/original/{}/{}/{}", sysTrainingProperties.getTenantCode(), sysTrainingProperties.getLeveId(), sysTrainingProperties.getMHmId());
        for (OriginalDataGenerator originalDataGenerator : originalDataGenerators) {
            originalDataGenerator.start(sysTrainingProperties.getMHmId(), new Consumer<String>() {
                @Override
                public void accept(String originalData) {
                    boolean published = mqttClient.publish(topic, originalData.getBytes(StandardCharsets.UTF_8), MqttQoS.valueOf(1));
                    log.info("Original data: {}  published {}", originalData, published);
                }
            });
        }
    }

}
